package com.video.netty.send;

import com.qf.entity.ResultData;
import com.video.commons.sendaop.ISocketSend;
import com.video.entity.Solution;
import com.video.netty.commons.utils.MsgUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 26.执行方案
 * {"id":"startSolutionTask","name":"夏季作息","account":"admin"}
 * 返回
 * {"id":"startSolutionTaskResponse", "response":"success","account":"admin"}
 * {"id":"startSolutionTaskResponse","response":"fail","account":"admin"}
 */
@Component
public class StartSolutionTaskSend extends ISocketSend {

    @Override
    protected void preMsg(String msgid) {
        //根据msgidc创建阻塞队列
        MsgUtil.createMsgQueue(msgid);
    }

    @Override
    protected Object postMsg(String msgid, Object result) {
        BlockingQueue blockQueue = MsgUtil.getBlockQueue(msgid);
        try {
            //获取阻塞状态
            String status = (String) blockQueue.poll(5, TimeUnit.SECONDS);
            System.out.println("获得阻塞状态：" + status);

            //如果返回结果为失败
            if (status != null && status.equals("fail")) {
                return new ResultData<Integer>().setCode(ResultData.ResultCodeList.ERROR).setData(0).setMsg("方案执行失败，确保当前方案下没有正在执行的任务！");
            }
        } catch (InterruptedException e) {
            //如果发生超时异常，则直接返回原本的返回值
            return result;
        } finally {
            //最终都会删除该阻塞队列
            MsgUtil.deleteMsgQueue(msgid);
        }
        return super.postMsg(msgid, result);
    }

    @Override
    public Map<String, Object> sendMsg(Object... objs) {
        Solution solution = (Solution) objs[0];

        Map<String, Object> map = new HashMap<>();
        map.put("id", "startSolutionTask");
        map.put("name", solution.getSolutionname());

        return map;
    }
}
